﻿using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.Serialization;

namespace Bing_Wallpaper_Downloader
{
    class Translator
    {
        public static string Translate(string appId, string text, string from, string to)
        {
            string translation = string.Empty;

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format("http://api.microsofttranslator.com/v2/Http.svc/Translate?appId={0}&text={1}&from={2}&to={3}", appId, text, from, to));

            WebResponse webResponse = httpWebRequest.GetResponse();

            using (Stream stream = webResponse.GetResponseStream())
            {
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(string));

                translation = (string)dataContractSerializer.ReadObject(stream);
            }

            return translation;
        }

        public static List<CultureInfo> Languages(string appId)
        {
            List<CultureInfo> languageList = new List<CultureInfo>();

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(string.Format("http://api.microsofttranslator.com/v2/Http.svc/GetLanguagesForTranslate?appId={0}", appId));

            WebResponse webResponse = httpWebRequest.GetResponse();

            using (Stream stream = webResponse.GetResponseStream())
            {
                DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(List<string>));

                List<string> languagesString = (List<string>)dataContractSerializer.ReadObject(stream);

                foreach (string language in languagesString)
                {
                    try
                    {
                        languageList.Add(new CultureInfo(language));
                    }
                    catch
                    { }
                }
            }

            return languageList;
        }
    }
}
